package cn.ddiancan.xddcloud.common.interceptor;

import java.util.Collection;
import java.util.Map;

import cn.ddiancan.xddcloud.common.context.CloudRequestContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.MultiValueMap;

@Slf4j
@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            // 如果当前线程初始化了上下文
            if (CloudRequestContext.isCurrentThreadInitialized()) {
                MultiValueMap<String, String> inComing = CloudRequestContext.getContextForCurrentThread().getInComing();
                Map<String, Collection<String>> headers = requestTemplate.headers();
                inComing.forEach(headers::putIfAbsent);
                // 处理feign请求头，防止外部头污染
                headers.forEach((headerName, value) -> {
                    requestTemplate.removeHeader(headerName);
                    requestTemplate.header(headerName, value);
                });
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
